import { useLocation, useNavigate } from "react-router-dom"
import AsideHeader from "../AsideHeader"
import { Menu, MenuValue } from "tdesign-react"
import { Icon } from 'tdesign-icons-react'
import menuStore from "@/store/menu";
import { MenuObject } from "types";

const { MenuItem, SubMenu } = Menu;

// 渲染菜单
function RenderMenu() {
    const { getMenu } = menuStore();

    const menuList = [...getMenu()]

    return (
        menuList.map(menuItem => {
            return hasChildrenMenu(menuItem) ? RenderChildMenu(menuItem, menuItem.children!) : <MenuItem key={menuItem.path} value={menuItem.path}>
                {menuItem.meta.title}
            </MenuItem>
        })

    )
}

// 递归子菜单
function RenderChildMenu(menu: MenuObject, menuList: MenuObject[]) {
    return (
        <SubMenu key={menu.path} icon={<Icon name={menu.icon} />} value={menu.path} title={menu.meta.title}>
            {
                menuList.map(childMenu => (
                    <MenuItem key={childMenu.path} value={childMenu.path}>
                        {childMenu.meta.title}
                        {hasChildrenMenu(childMenu) && RenderChildMenu(childMenu, childMenu.children!)}
                    </MenuItem>
                ))
            }
        </SubMenu>
    )
}

// 判断是否有 children
function hasChildrenMenu(menu: MenuObject) {
    return menu.children && menu.children.length > 0
}


// 菜单组件
const MenuAside = () => {

    const nav = useNavigate();

    const location = useLocation();

    function handleChange(path: MenuValue) {
        nav(path as string);
    }

    return (
        <>

            <Menu value={location.pathname} logo={<AsideHeader />} className="pt-[-10px]" onChange={(v) => handleChange(v)}>
                <MenuItem key="/" value="/">
                    首页
                </MenuItem>
                <RenderMenu />
            </Menu>
        </>
    )
}

export default MenuAside;